package com.itheima.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author liudo
 * @version 1.0
 * @project tlias-backend
 * @date 2023/9/13 17:04:07
 */
@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut("@annotation(com.itheima.annotation.InsertOrUpdate)")
    public void pt() {

    }

    @Before("pt()")
    public void autoFill(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Object arg = args[0];
        // 反射 setCreateTime(LocalDateTime) 自动注入
        Class<?> aClass = arg.getClass();
        try {
            // insert update
            Method setCreateTime = aClass.getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateTime = aClass.getDeclaredMethod("setUpdateTime", LocalDateTime.class);

            setCreateTime.invoke(arg, LocalDateTime.now());
            setUpdateTime.invoke(arg, LocalDateTime.now());
        } catch (Exception e) {
            log.error("-------------反射出错了", e);
        }
    }
}
